import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { nextTick } from 'vue'
import Home from '../views/sow/Home.vue'
import Login from '../views/zzy/Login.vue'
import VerificationLogin from '../views/zzy/VerificationLogin.vue'
import Register from '../views/zzy/Register.vue'
import UserManagement from '../views/zzy/UserManagement.vue'
import TestPage from '../views/zzy/TestPage.vue'
import PasswordLogin from '../views/zzy/PasswordLogin.vue'

import FaceRecognition from '../views/zzy/FaceRecognition.vue'
import HospitalDashboard from '@/views/dashboard/HospitalDashboard.vue'

// 路由懒加载函数
const lazyLoad = (view: string) => {
  return () => import(`../views/sow/${view}.vue`)
}

// 带预加载的懒加载函数
const lazyLoadWithPreload = (view: string, preloadViews: string[] = []) => {
  const component = () => import(`../views/sow/${view}.vue`)
  
  // 预加载相关组件
  if (preloadViews.length > 0) {
    nextTick(() => {
      preloadViews.forEach(preloadView => {
        import(`../views/sow/${preloadView}.vue`)
      })
    })
  }
  
  return component
}

// 路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/guide-entry'
  },
  {
    path: '/guide-entry',
    name: 'GuideEntry',
    component: () => import('../views/zzy/GuideEntry.vue'),
    meta: {
      title: '欢迎使用',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/guide',
    name: 'Guide',
    component: () => import('../views/zzy/GuideContainer.vue'),
    meta: {
      title: '使用引导',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/home',
    name: 'Home',
    component: lazyLoadWithPreload('Home', ['DepartmentSelect', 'HospitalSelect']),
    meta: {
      title: '首页',
      keepAlive: true,
      requiresAuth: false
    }
  },
  {
    path: '/medical-home',
    name: 'MedicalHome',
    component: () => import('../views/sow/MedicalHome.vue'),
    meta: {
      title: '医疗首页',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/user-profile-edit',
    name: 'UserProfileEdit',
    component: () => import('../views/sow/UserProfileEdit.vue'),
    meta: {
      title: '编辑资料',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/prescription-drug',
    name: 'PrescriptionDrug',
    component: () => import('../views/sow/PrescriptionDrug.vue'),
    meta: {
      title: '处方药',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/medical-records',
    name: 'MedicalRecords',
    component: () => import('../views/sow/MedicalRecords.vue'),
    meta: {
      title: '医疗记录',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/physical-examination-reports',
    name: 'PhysicalExaminationReports',
    component: () => import('../views/sow/PhysicalExaminationReports.vue'),
    meta: {
      title: '体检报告',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/health-data',
    name: 'HealthData',
    component: () => import('../views/sow/HealthData.vue'),
    meta: {
      title: '健康数据',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/step-tracking',
    name: 'StepTracking',
    component: () => import('../views/sow/StepTracking.vue'),
    meta: {
      title: '步数',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/weight-tracking',
    name: 'WeightTracking',
    component: () => import('../views/sow/WeightTracking.vue'),
    meta: {
      title: '体重',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/blood-pressure-tracking',
    name: 'BloodPressureTracking',
    component: () => import('../views/sow/BloodPressureTracking.vue'),
    meta: {
      title: '血压',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/department-select',
    name: 'DepartmentSelect',
    component: lazyLoadWithPreload('DepartmentSelect', ['DepartmentSearch', 'HospitalSelect']),
    meta: {
      title: '选择科室',
      keepAlive: true,
      requiresAuth: false
    }
  },
  {
    path: '/department-search',
    name: 'DepartmentSearch',
    component: lazyLoad('DepartmentSearch'),
    meta: {
      title: '搜索科室',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/hospital-select',
    name: 'HospitalSelect',
    component: lazyLoadWithPreload('HospitalSelect', ['HospitalDetail', 'DoctorSelect']),
    meta: {
      title: '选择医院',
      keepAlive: true,
      requiresAuth: false
    }
  },
  {
    path: '/hospital-detail/:id?',
    name: 'HospitalDetail',
    component: lazyLoadWithPreload('HospitalDetail', ['DoctorSelect']),
    meta: {
      title: '医院详情',
      keepAlive: false,
      requiresAuth: false
    },
    props: true
  },
  {
    path: '/doctor-select',
    name: 'DoctorSelect',
    component: lazyLoad('DoctorSelect'),
    meta: {
      title: '选择医生',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/doctor-detail/:id?',
    name: 'DoctorDetail',
    component: lazyLoad('DoctorDetail'),
    meta: {
      title: '医生详情',
      keepAlive: false,
      requiresAuth: false
    },
    props: true
  },
  {
    path: '/human-body',
    name: 'HumanBody3D',
    component: () => import('../views/anatomy/MobileHumanBody.vue'),
    meta: {
      title: '高级3D医学查看器',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/time-select',
    name: 'TimeSelect',
    component: lazyLoad('TimeSelect'),
    meta: {
      title: '选择时间',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/patient-select',
    name: 'PatientSelect',
    component: lazyLoad('PatientSelect'),
    meta: {
      title: '选择就诊人',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/add-patient',
    name: 'AddPatient',
    component: lazyLoad('AddPatient'),
    meta: {
      title: '添加就诊人',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/appointment-confirm',
    name: 'AppointmentConfirm',
    component: lazyLoad('AppointmentConfirm'),
    meta: {
      title: '预约确认',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/payment',
    name: 'Payment',
    component: lazyLoad('Payment'),
    meta: {
      title: '选择支付方式',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/payment-success',
    name: 'PaymentSuccess',
    component: lazyLoad('PaymentSuccess'),
    meta: {
      title: '支付成功',
      keepAlive: false,
      requiresAuth: false
    }
  }
  ,
  {
    path: '/pharmacy',
    name: 'PharmacyHome',
    component: lazyLoad('PharmacyHome'),
    meta: {
      title: '网上药房',
      keepAlive: true,
      requiresAuth: false
    }
  },
          {
          path: '/all-products',
          name: 'AllProducts',
          component: lazyLoad('AllProducts'),
          meta: {
            title: '全部产品',
            keepAlive: false,
            requiresAuth: false
          }
        },
        {
          path: '/product/:id',
          name: 'ProductDetail',
          component: lazyLoad('ProductDetail'),
          meta: {
            title: '商品详情',
            keepAlive: false,
            requiresAuth: false
          }
        },
  {
    path: '/about',
    name: 'About',
    component: lazyLoad('About'),
    meta: {
      title: '关于我们',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue'),
    meta: {
      title: '页面未找到',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/verification-login',
    name: 'VerificationLogin',
    component: VerificationLogin
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/user-management',
    name: 'UserManagement',
    component: UserManagement
  },
  {
    path: '/test',
    name: 'TestPage',
    component: TestPage
  },
  {
    path: '/password-login',
    name: 'PasswordLogin',
    component: PasswordLogin
  },
  {
    path: "/zxl",
    name: "zxl",
    component: () => import("../views/zxl/Ai.vue"),
  },
  // LHX 聊天模块路由
  {
    path: "/lhx-patient-chat",
    name: "LhxPatientChat",
    component: () => import("../views/lhx/LhxPatientChatList.vue"),
  },
 
  {
    path: '/disease-symptoms',
    name: 'DiseaseSymptoms',
    component: () => import('../views/sow/DiseaseSymptoms.vue'),
    meta: {
      title: '疾病症状',
      keepAlive: false,
      requiresAuth: false
    }
  },
  {
    path: '/shopping-cart',
    name: 'ShoppingCart',
    component: lazyLoad('ShoppingCart'),
    meta: {
      title: '购物车',
      keepAlive: false,
      requiresAuth: false
    }
  },
        {
  path: '/confirm-order',
  name: 'ConfirmOrder',
  component: lazyLoad('ConfirmOrder'),
  meta: {
    title: '确认订单',
    keepAlive: false,
    requiresAuth: false
  }
},
{
  path: '/order-details',
  name: 'OrderDetails',
  component: lazyLoad('OrderDetails'),
  meta: {
    title: '订单详情',
    keepAlive: false,
    requiresAuth: false
  }
},
  {
    path: '/dashboard',
    name: 'dashboard',
    component: HospitalDashboard,
    meta: {
      title: '医院实时监控'
    }
  },
  {
    path: "/lhx-doctor-chat",
    name: "LhxDoctorChat",
    component: () => import("../views/lhx/LhxDoctorChatList.vue"),
  },
  {
    path: "/lhx-chat",
    name: "LhxChat",
    component: () => import("../views/lhx/LhxChatWindow.vue"),
  },
  {
    path: "/lhx-demo",
    name: "LhxDemo",
    component: () => import("../views/lhx/LhxDemo.vue")
  },
  {
    path: "/face-recognition",
    name: "FaceRecognition",
    component: FaceRecognition
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 路由切换时的滚动行为
    if (savedPosition) {
      return savedPosition
    } else if (to.hash) {
      return {
        el: to.hash,
        behavior: 'smooth'
      }
    } else {
      return { top: 0 }
    }
  }
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta?.title) {
    document.title = `${to.meta.title} - 医疗预约系统`
  }
  
  // 检查引导页逻辑
  // const guideCompleted = localStorage.getItem('guideCompleted')  // 临时注释，测试用
  
  // 如果用户访问根路径或引导相关页面，且已完成引导，则重定向到登录页
  // if ((to.path === '/' || to.path === '/guide-entry' || to.path === '/guide') && guideCompleted === 'true') {
  //   next('/login')
  //   return
  // }
  
  // 页面加载进度条（可选）
  if (typeof window !== 'undefined') {
    const loadingElement = document.getElementById('loading')
    if (loadingElement) {
      loadingElement.style.display = 'block'
    }
  }
  
  next()
})

// 全局后置钩子
router.afterEach((to, from) => {
  // 隐藏加载进度条
  if (typeof window !== 'undefined') {
    const loadingElement = document.getElementById('loading')
    if (loadingElement) {
      loadingElement.style.display = 'none'
    }
  }
  
  // 页面访问统计（可选）
  if (import.meta.env.VITE_ENABLE_ANALYTICS === 'true') {
    // 这里可以添加页面访问统计代码
    console.log(`页面访问: ${to.path}`)
  }
})

// 路由错误处理
router.onError((error) => {
  console.error('路由错误:', error)
  // 可以在这里添加错误上报逻辑
})

export default router
